package com.hd.core.project.module.service;

import com.hd.core.project.module.domain.Select2;
import com.hd.core.project.module.domain.Student;
import com.hd.core.project.module.domain.Dormitory;

import com.hd.core.project.module.mapper.DormitoryMapper;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * 宿舍管理-服务层
 * 
 * <br/>
 * @since JDK 1.8
 * @version  V1.0
 * @author RichardTang 
 * @date: 2018年8月20日
 * @package com.hd.core.project.module.service
 * @copyright:Copyright (c) 2018, 1245811923@qq.com All Rights Reserved.
 */
@Service
public class DormitoryService extends ServiceImpl<DormitoryMapper,Dormitory> {

	@Autowired
	private StudentService studentListService;
	
	/**
	 * <p>添加一个宿舍信息并且更新相关的学生表</p>
	 * 
	 * @param entity 数据实体
	 * @param ids 需要更新的学生表对应的id
	 * @return 处理结果
	 */
	@Transactional
	public boolean insert(Dormitory entity,String[] ids) {
		//添加宿舍信息表
		baseMapper.insert(entity);
		//更新学生表信息
		List<Student> students = new ArrayList<Student>();
		for(int i = 0;i < ids.length;i++) {
			Student studentItem = new Student();
			studentItem.setId(ids[i]);
			studentItem.setNowDormitoryId(entity.getId());
			students.add(studentItem);
		}
		return studentListService.updateBatchById(students);
	}

	/**
	 * <p>根据id查询宿舍列表信息</p>
	 * 
	 * @param id 宿舍id
	 * @return 查询到的宿舍
	 */
	public Dormitory selectDormById(Integer id) {
		return baseMapper.selectDormById(id);
	}

	/**
	 * <p>根据id来更新宿舍信息</p>
	 * <p>并且更新对应的学生的信息</p>
	 * 
	 * @param entity 数据实体
	 * @param ids 学生id
	 * @return 受影响的行数
	 */
	@Transactional
	public Integer updateDormById(Dormitory entity,List<String> ids) {
		Integer result = 0;
		Integer dormId = entity.getId();
		result = baseMapper.updateById(entity);
		result += studentListService.updateDormByField(0,"now_dormitory_id",dormId.toString());
		result += studentListService.updateDormByField(dormId,ids,"id");
		return result;
	}

	/**
	 * <p>根据id删除宿舍并且设置对应的学生状态</p>
	 * 
	 * @param ids 需要被删除的宿舍id
	 * @return 受影响的行数
	 */
	@Transactional
	public Integer deleteDormByIds(List<String> ids) {
		Integer result = 0;
		result += baseMapper.deleteBatchIds(ids);
		result += studentListService.updateDormByField(0,ids,"now_dormitory_id");
		return result;
	}

	/**
	 * <p>根据条件实体查询宿舍</p>
	 * 
	 * @param entity 条件实体
	 * @return 符合条件的数据
	 */
	public List<Dormitory> selectList(Dormitory entity) {
		return baseMapper.selectList(entity);
	}

	/**
	 * <p>查询宿舍信息 以select2格式返回</p>
	 * 
	 * @return select2格式宿舍数据
	 */
	public List<Select2> selectList() {
		return baseMapper.selectList();
	}
}
